import { loadingText, messageDuration } from '@/config'
import { Loading, Message, MessageBox, Notification } from 'element-ui'

const install = (Vue) => {
  /* 全局加载层 */
  Vue.prototype.$loading = (index, text) => {
    let loading
    if (!index) {
      loading = Loading.service({
        lock: true,
        text: text || loadingText,
        background: 'hsla(0,0%,100%,.8)',
      })
    } else {
      loading = Loading.service({
        lock: true,
        text: text || loadingText,
        spinner: 'vab-loading-type' + index,
        background: 'hsla(0,0%,100%,.8)',
      })
    }
    return loading
  }

  Vue.prototype.$message = (message, type) => {
    Message({
      offset: 60,
      showClose: true,
      message: message,
      type,
      dangerouslyUseHTMLString: true,
      duration: messageDuration,
    })
  }

  Vue.prototype.$alert = (content, title, callback) => {
    MessageBox.alert(content, title || '温馨提示', {
      confirmButtonText: '确定',
      dangerouslyUseHTMLString: true,
      callback: (action) => {
        if (callback) {
          callback()
        }
      },
    })
  }

  /**
   * 确认方法
   * @param {content: string, title: string, onConfirmed?: Function, onCanceled?: Function  } arg
   */
  Vue.prototype.$confirm = ({
    content,
    title,
    onConfirmed,
    onCanceled,
  } = arg) => {
    MessageBox.confirm(content, title || '温馨提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        typeof onConfirmed === 'function' && onConfirmed()
      })
      .catch(() => {
        typeof onCanceled === 'function' && onCanceled()
      })
  }

  /**
   * 提醒信息
   * @param {{ message: string, title; string, type: string?, position?: string}} args
   */
  Vue.prototype.$notify = ({ message, title, type, position } = args) => {
    Notification({
      title: title,
      message: message,
      position: position || 'top-right',
      type: type || 'success',
      duration: messageDuration,
    })
  }

  /* 全局事件总线 */
  Vue.prototype.$baseEventBus = new Vue()
}

if (typeof window !== 'undefined' && window.Vue) {
  install(window.Vue)
}

export default install
